package com.atguigu.gmall.index.aspect;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.index.annotation.GmallCache;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class GmallCacheAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RBloomFilter bloomFilter;
    /**
     * 1.方法必须返回Object
     * 2.方法必须要有ProceedingJoinPoint参数
     * 3.方法必须抛出Throwable异常
     * 4.必须手动执行目标方法
     *
     * 获取目标方法参数：joinPoint.getArgs()
     * 目标对象：joinPoint.getTarget()
     * 方法对象签名：(MethodSignature) joinPoint.getSignature()
     */
    @Around("@annotation(com.atguigu.gmall.index.annotation.GmallCache)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 目标方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取目标方法对象
        Method method = signature.getMethod();
        // 获取目标方法上的GmallCache注解对象
        GmallCache gmallCache = method.getAnnotation(GmallCache.class);
        // 获取缓存的前缀
        String prefix = gmallCache.prefix();

        // 拼接缓存的key
        String args = StringUtils.join(joinPoint.getArgs(), ",");
        String key = prefix + args;

        // 为了防止缓存穿透，使用布隆过滤器
        if (!bloomFilter.contains(key)) {
            return null;
        }
        // 1.查询缓存，如果缓存中命中，则直接返回
        String json = this.redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(json)){
            return JSON.parseObject(json, signature.getReturnType());
        }

        // 2.添加分布式锁，防止缓存击穿
        String lock = gmallCache.lock();
        RLock rLock = this.redissonClient.getLock(lock + args);
        rLock.lock();

        try {
            // 3.再查缓存，获取分布式锁的过程中，可能有其他请求放入了缓存
            String json2 = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(json2)){
                return JSON.parseObject(json2, signature.getReturnType());
            }

            // 4.执行目标方法
            Object result = joinPoint.proceed(joinPoint.getArgs());

            // 5.放入缓存（缓存雪崩 释放分布式锁）
            if (result != null) {
                int timeout = gmallCache.timeout() + new Random().nextInt(gmallCache.random());
                this.redisTemplate.opsForValue().set(key, JSON.toJSONString(result), timeout, TimeUnit.MINUTES);
            }
            return result;
        } finally {
            rLock.unlock();
        }
    }

    @Pointcut("execution(* com.atguigu.gmall.index.service.*.*(..))")
    public void pointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("2前置通知。。。。。。");
    }

    @AfterReturning("pointcut()")
    public void afterReturning(){
        System.out.println("4返回后通知。。。。。。");
    }

    @AfterThrowing("execution(* com.atguigu.gmall.index.service.*.*(..))")
    public void afterThrowing(){
        System.out.println("异常后通知。。。。。。");
    }

    @After("execution(* com.atguigu.gmall.index.service.*.*(..))")
    public void after(){
        System.out.println("5最终通知。。。。。。");
    }


}
